package service

import (
	"boy-go/modules/system/model"
	"boy-go/modules/system/vo"
)

func NewSysPermissionService() SysPermissionService {
	return &sysPermissionService{}
}

type sysPermissionService struct {
}

func (s *sysPermissionService) GetRolePermission(sysUser model.SysUser) []*string {
	roles := make([]*string, 0)
	if sysUser.IsAdmin() {
		admin := "admin"
		roles = append(roles, &admin)
	} else {
		roles = NewSysRoleService().SelectRolePermissionByUserId(sysUser.UserId)
	}
	return roles
}

func (s *sysPermissionService) GetMenuPermission(sysUser model.SysUser) []*string {
	perms := make([]*string, 0)
	if sysUser.IsAdmin() {
		// 超级管理员 拥有所有权限
		rootPerm := "*:*:*"
		perms = append(perms, &rootPerm)
	} else {
		menuService := NewSysMenuService()
		roles := NewSysRoleService().SelectRolesByUserId(sysUser.UserId)
		if roles != nil || len(roles) > 0 {
			for _, role := range roles {
				if role.Status != nil && *role.Status == "0" && role.RoleId != 1 {
					rolePerms := menuService.SelectMenuPermsByRoleId(role.RoleId)
					perms = append(perms, rolePerms...)
				}
			}
		} else {
			uPerms := menuService.SelectMenuPermsByRoleId(sysUser.UserId)
			perms = append(perms, uPerms...)
		}
	}
	return perms
}
func (s *sysPermissionService) GetMenuPermissionMap(user *vo.SysUserModel) map[string]bool {
	perms := map[string]bool{}
	if model.IsAdmin(&user.UserId) {
		// 超级管理员 拥有所有权限
		rootPerm := "*:*:*"
		perms[rootPerm] = true
	} else {
		menuService := NewSysMenuService()
		roles := user.Roles
		if roles != nil || len(roles) > 0 {
			for _, role := range roles {
				if role.Status != nil && *role.Status == "0" && role.RoleId != 1 {
					rolePerms := menuService.SelectMenuPermsByRoleId(role.RoleId)
					permissionMap := map[string]bool{}
					for _, rolePerm := range rolePerms {
						if rolePerm != nil && *rolePerm != "" {
							perms[*rolePerm] = true
							permissionMap[*rolePerm] = true
						}
					}
					role.PermissionMap = permissionMap
				}
			}
		} else {
			uPerms := menuService.SelectMenuPermsByRoleId(user.UserId)
			for _, uPerm := range uPerms {
				if uPerm != nil && *uPerm != "" {
					perms[*uPerm] = true
				}
			}
		}
	}
	return perms
}
func (s *sysPermissionService) GetRolePermissionByUserId(userId int64) []*string {
	roles := make([]*string, 0)
	if model.IsAdmin(&userId) {
		admin := "admin"
		roles = append(roles, &admin)
	} else {
		roles = NewSysRoleService().SelectRolePermissionByUserId(userId)
	}
	return roles
}
func (s *sysPermissionService) GetMenuPermissionByUserId(userId int64) []*string {
	perms := make([]*string, 0)
	if model.IsAdmin(&userId) {
		root := "*:*:*"
		perms = append(perms, &root)
	} else {
		//roles, err := NewSysRoleService().List()
	}
	return perms
}
